package com.corechina.apex_osswords.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.corechina.apex_osswords.common.APEXOSSWordsException;
import com.corechina.apex_osswords.common.Response;
import com.corechina.apex_osswords.common.ShiroUtils;
import com.corechina.apex_osswords.domain.dao.SysUserMapper;
import com.corechina.apex_osswords.domain.entity.SysUser;
import com.corechina.apex_osswords.domain.vo.SysUserVo;
import com.corechina.apex_osswords.service.ISysUser;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: apex_osswords
 * @description: 用户管理逻辑实现类
 * @author: cc
 * @create: 2022-03-03 09:23
 **/

@Service
public class SysUserImpl implements ISysUser {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response add(SysUser sysUser) {
        String salt = RandomStringUtils.randomAlphanumeric(20);
        if (sysUser.getPwd() == null || sysUser.getPwd().trim().equals("")) {
            sysUser.setPwd(new Md5Hash(new Md5Hash("Apex@1234").toString(), salt).toString());
        }
        sysUser.setSalt(salt);
        if (null == sysUser || sysUser.getPwd() == null) {
            throw new APEXOSSWordsException("密码不能为空", String.format("SysUserService save parameter error! param: %s", sysUser));
        }

        if (isLoginNameUsed(sysUser.getLoginName())) {
            throw new APEXOSSWordsException("登录名已存在!");
        }

        if (sysUserMapper.insert(sysUser) < 1) {
            throw new APEXOSSWordsException("保存用户信息失败", String.format("SysUserService save parameter error! param: %s", sysUser));
        }
        return Response.ok(sysUser.getId());
    }

    /**
     * 用户名是否存在
     *
     * @param loginName
     * @return
     */
    private boolean isLoginNameUsed(String loginName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        if (sysUserMapper.selectCount(queryWrapper) >= 1) {
            return true;
        }
        return false;
    }


    public Response update(SysUser sysUser) {
        sysUserMapper.updateByPrimaryKey(sysUser);
        return Response.ok();
    }

    public Response getOne(Integer id) {
        return Response.ok(sysUserMapper.getOne(id));
    }

    @Override
    public Response getUserAllList(String userName, Integer pageIndex, Integer pageSize) {
        IPage<SysUserVo> sysUserVoIPage = sysUserMapper.getUserAllList(new Page<>(pageIndex, pageSize), userName);
        return Response.ok(sysUserVoIPage.getRecords(), sysUserVoIPage.getTotal());
    }

    @Override
    public Response updatePwd(String oldPwd, String newPwd) {
        if (oldPwd == null || oldPwd.trim().equals("")) {
            return Response.error("原密码不能为空");
        } else if (newPwd == null || newPwd.trim().equals("")) {
            return Response.error("新密码不能为空");
        } else {
            SysUser sysUser = sysUserMapper.selectById(ShiroUtils.getUserId());
            oldPwd = new Md5Hash(oldPwd, sysUser.getSalt()).toString();
            if (!oldPwd.equals(sysUser.getPwd())) {
                return Response.error("原密码错误");
            }
            newPwd = new Md5Hash(newPwd, sysUser.getSalt()).toString();
            sysUserMapper.updatePwd(newPwd, ShiroUtils.getUserId());
            return Response.ok();
        }
    }

    @Override
    public Response resetPwd(Integer id, String newPwd) {
        if (id == null) {
            return Response.error("用户ID不能为空");
        }
        SysUser sysUser = sysUserMapper.selectById(id);
        newPwd = new Md5Hash(new Md5Hash(newPwd).toString(), sysUser.getSalt()).toString();
        sysUserMapper.updatePwd(newPwd, id);
        return Response.ok();
    }

    @Override
    public SysUser getByLoginName(String loginName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public Response del(Integer id) {
        sysUserMapper.deleteById(id);
        return Response.ok();
    }
}
